﻿using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Repository;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using WinForm_Mes.ProductManagement.BaseSetting;
using WinForm_Mes.ProductManagement.Product;

namespace WinForm_Mes.ProductManagement
{
    public partial class ProductSpecificationForm : DevExpress.XtraEditors.XtraForm
    {
        // 基础数据接口地址
        private string baseUrl = "http://localhost:5164";
        private HttpClient httpClient;
        public ProductSpecificationForm()
        {
            InitializeComponent();
            this.Text = "规格";
            httpClient = new HttpClient();
            InitializeEvents();
        }
        // 绑定按钮事件
        private void InitializeEvents()
        {
            //查询按钮点击事件
            SearchButton.Click += SearchSpecification;
            //重置按钮点击事件
            ResetButton.Click += ResetSpecification;
            //新增按钮点击事件
            AddButton.Click+= AddSpecification;
            //删除按钮点击事件
            DeleteButton.Click+= DeleteSpecification;
            // 修改按钮点击事件
            UpdateButton.Click+= UpdateSpecification;
        }
        public void Specification_Load(object sender, EventArgs e)
        {
            LoadSpecificationData();
        }
        //加载规格数据
        private async Task LoadSpecificationData()
        {
            try
            {
                // 显示提示信息
                gridControl1.DataSource = null;
                // 调用后端API获取数据
                HttpResponseMessage response = await httpClient.GetAsync(baseUrl + "/api/Specification/GetAllSpecification");
                if (response.IsSuccessStatusCode)
                {
                    string jsonContent = await response.Content.ReadAsStringAsync();
                    var apiResponse = JsonConvert.DeserializeObject<ApiResponse<SpecificationModels>>(jsonContent);
                    var models = apiResponse.Items;
                    // 绑定数据到表格
                    gridControl1.DataSource = models;
                    // 设置列映射
                    gridView1.Columns["Id"].Visible = false;
                    gridView1.Columns["TypeId"].Visible = true;
                    gridView1.Columns["SpecificationCode"].Caption = "规格编号";
                    gridView1.Columns["SpecificationName"].Caption = "规格名称";
                    gridView1.Columns["CreateTime"].Caption = "创建时间";
                }
                else
                {
                    MessageBox.Show("获取规格数据失败！");
                }
            }
            catch (Exception ex)
            {

                MessageBox.Show("发生错误：" + ex.Message);
            }
        }
        //查询规格数据
        private async void SearchSpecification(object sender, EventArgs e)
        {
            try
            {
                var TypeId = textSearchTypeId.Text.Trim();
                string queryParams = "?";
                if (TypeId!=null)
                {
                    queryParams += $"TypeId={TypeId}&";
                }
                // 去掉最后一个 & 号
                if (queryParams.EndsWith("&"))
                {
                    queryParams = queryParams.Substring(0, queryParams.Length - 1);
                }
                // 如果只有问号则不附加参数
                if (queryParams == "?")
                {
                    queryParams = "";
                }
                HttpResponseMessage response = await httpClient.GetAsync(baseUrl + "/api/Specification/GetAllSpecification" + queryParams);
                if (response.IsSuccessStatusCode)
                {
                    string jsonContent = await response.Content.ReadAsStringAsync();
                    var apiResponse = JsonConvert.DeserializeObject<ApiResponse<SpecificationModels>>(jsonContent);
                    var Specifications = apiResponse.Items;
                    // 绑定数据到表格
                    gridControl1.DataSource = Specifications;
                }
                else
                {
                    MessageBox.Show("查询规格型号数据失败！");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("查询发生错误：" + ex.Message);
            }
        }
        //重置规格数据
        private async void ResetSpecification(object sender, EventArgs e)
        {
            textSearchTypeId.Text ="";
            LoadSpecificationData();
        }
        //添加规格数据
        private async void AddSpecification(object sender, EventArgs e)
        {
            using (var addSpecificationForm = new AddSpecificationForm())
            {
                if (addSpecificationForm.ShowDialog() == DialogResult.OK)
                {
                    LoadSpecificationData();
                };
            }
        }
        // 获取要删除的选中行
        private SpecificationModels GetSelectedItem()
        {
            if (gridView1.GetSelectedRows().Length > 0)
            {
                int rowHandle = gridView1.GetSelectedRows()[0];
                return gridView1.GetRow(rowHandle) as SpecificationModels;
            }
            return null;
        }
        //删除规格数据
        private async void DeleteSpecification(object sender, EventArgs e)
        {
            var selected = GetSelectedItem();

            if (selected == null)
            {
                MessageBox.Show("请选择要删除的数据！");
                return;
            }
            if (gridView1.GetSelectedRows().Length > 1)
            {
                MessageBox.Show("只能选择一条数据进行删除！");
                return;
            }
            if (MessageBox.Show("确定要删除吗？", "提示", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                using (var client = new HttpClient())
                {
                    client.BaseAddress = new Uri("http://localhost:5164");
                    var response = await client.PostAsync($"/api/Specification/DelSpecification?Id={selected.Id}", null);
                    if (response.IsSuccessStatusCode)
                    {
                        MessageBox.Show("删除成功！");
                        await LoadSpecificationData();
                    }
                    else
                    {
                        MessageBox.Show("删除失败！");
                    } 
                }
            }
        }
        //反填规格数据
        private async void UpdateSpecification(object sender, EventArgs e)
        {
            var selected = GetSelectedItem();
            if (selected == null)
            {
                MessageBox.Show("请选择要修改的数据！");
                return;
            }
            if (gridView1.GetSelectedRows().Length > 1)
            {
                MessageBox.Show("只能选择一条数据进行修改！");
                return;
            }
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri("http://localhost:5164");
                var response = await client.GetAsync($"/api/Specification/GetSpecificationCount?Id={selected.Id}");
                if (response.IsSuccessStatusCode)
                {
                    var json=await response.Content.ReadAsStringAsync();
                    var apiResponse = JsonConvert.DeserializeObject<ApiResponse<int>>(json);
                    var count = apiResponse.Items;
                    //选中要修改的行弹出修改窗口
                    UpdateSpecificationForm updateSpecificationForm = new UpdateSpecificationForm();
                    updateSpecificationForm.StartPosition = FormStartPosition.CenterParent;
                    if (updateSpecificationForm.ShowDialog() == DialogResult.OK)
                    {
                        await LoadSpecificationData();
                    }
                }
                else
                {
                    MessageBox.Show("获取失败！");
                }
            }
        }
        // 型号数据模型
        public class SpecificationModels
        {
            /// <summary>
            /// 主键Id
            /// </summary>
            public long Id { get; set; }
            /// <summary>
            /// 规格型号
            /// </summary>
            public long TypeId { get; set; }
            /// <summary>
            /// 规格编码
            /// </summary>
            public string SpecificationCode { get; set; }
            /// <summary>
            /// 规格名称
            /// </summary>
            public string SpecificationName { get; set; }
            /// <summary>
            /// 创建时间
            /// </summary>
            public DateTime CreateTime { get; set;}
        }
        // API响应包装类
        public class ApiResponse<T>
        {
            public int Total { get; set; } = 0;
            public int Index { get; set; } = 1;
            public int Size { get; set; } = 10;
            public List<T> Items { get; set; } = new List<T>();
        }
    }
}